package com.xinchuang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinchuang.comment.R;
import com.xinchuang.domain.entity.TestCron;
import com.xinchuang.mapper.TestCronMapper;
import com.xinchuang.schedule.TryOutPlanSchedule;
import com.xinchuang.service.CronService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:定时相关 ServiceImpl
 * @Author: thh
 * @Date: 2024/4/9 10:47
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CronServiceImpl implements CronService {

    private final TestCronMapper cronMapper;
    private final TryOutPlanSchedule tryOutPlanSchedule;

    @Value("${cron.class-name}")
    private String cronClassName;
    @Value("${cron.method-name}")
    private String cronMethodName;

    /**
     * 定时列表
     *
     * @return
     */
    @Override
    public String cronList() {
        List<TestCron> cronList = cronMapper.selectList(new LambdaQueryWrapper<TestCron>().orderByAsc(TestCron::getCreateTime));
        List<Map<String, String>> list = cronList.stream().map(cron -> {
            Map<String, String> map = new HashMap<>();
            map.put("id", cron.getId());
            map.put("cronExpression", cron.getCronExpression());
            return map;
        }).collect(Collectors.toList());
        return JSON.toJSONString(R.data(list));
    }

    /**
     * 添加定时
     *
     * @param jsonObject
     * @return
     */
    @Override
    public String addCron(JSONObject jsonObject) {
        String cronExpression = jsonObject.getString("cronExpression");
        if (StringUtils.isNotBlank(cronExpression)) {
            TestCron testCron = new TestCron();
            testCron.setClassName(cronClassName);
            testCron.setMethodName(cronMethodName);
            testCron.setCronExpression(cronExpression);
            int i = cronMapper.insert(testCron);
            if (i > 0) {
                try {
                    tryOutPlanSchedule.startTask(testCron.getId(), cronExpression);
                } catch (Exception e) {
                    log.error("添加定时失败:{}", e);
                }
                return JSON.toJSONString(R.success("添加成功"));
            }
        }

        return JSON.toJSONString(R.success("添加失败"));
    }

    /**
     * 修改定时
     *
     * @param jsonObject
     * @return
     */
    @Override
    public String editCron(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        if (StringUtils.isNotBlank(id)) {
            String cronExpression = jsonObject.getString("cronExpression");
            TestCron testCron = new TestCron();
            testCron.setId(id);
            testCron.setClassName(cronClassName);
            testCron.setMethodName(cronMethodName);
            testCron.setCronExpression(cronExpression);
            int i = cronMapper.updateById(testCron);
            if (i > 0) {
                try {
                    tryOutPlanSchedule.startTask(id, cronExpression);
                } catch (Exception e) {
                    log.error("重置定时失败:{}", e);
                }
                return JSON.toJSONString(R.success("编辑成功"));
            }
        }

        return JSON.toJSONString(R.success("编辑失败"));
    }
}
